import 'dart:typed_data';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
// import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:totaldemo/utils/util.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'dart:ui' as ui;
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:fluttertoast/fluttertoast.dart';

class SaveImgPage extends StatefulWidget {
  const SaveImgPage({Key key}) : super(key: key);
  @override
  _SaveImgPageState createState() => _SaveImgPageState();
}

class _SaveImgPageState extends State<SaveImgPage> {
  GlobalKey globalKey = GlobalKey();
  @override
  Widget build(BuildContext context) {
//CustomWidgets.appBarWhite(context, '会议详情'),
    return Scaffold(
      appBar: AppBar(
        title: Text('保存图'),
      ),
      body: Container(
          child: Column(
        children: [
          RepaintBoundary(
            key: globalKey,
            child: QrImage(
              data: '2',
              size: 250,
            ),
          ),
          ElevatedButton(
              onPressed: () {
                // print(globalKey.currentContext);
                // print(pngBytes);

                // AppUtil.saveImage('${image}', isAsset: true);
                _saveScreen();
              },
              child: Text('保存图片'))
        ],
      )),
    );
  }

  _toastInfo(String info) {
    Fluttertoast.showToast(msg: info, toastLength: Toast.LENGTH_LONG);
  }

  _saveScreen() async {
    RenderRepaintBoundary boundary =
        globalKey.currentContext.findRenderObject() as RenderRepaintBoundary;
    ui.Image image = await boundary.toImage();
    ByteData byteData =
        await (image.toByteData(format: ui.ImageByteFormat.png));
    if (byteData != null) {
      final result =
          await ImageGallerySaver.saveImage(byteData.buffer.asUint8List());
      print(result);
      _toastInfo(result.toString());
    }
  }
}
